const isAuthorized = require('./isAuthorized');
const jsonServer = require('json-server');
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const express = require('express');

// 自定义中间件
server.use((req, res, next) => {
  // 修改响应数据结构和字段命名
  res.jsonp = (data) => {
    const isSuccess = String(res.statusCode).startsWith('2')
    const response = {
      code: isSuccess ? 200 : res.statusCode,
      msg: isSuccess ? '成功' : '失败',
      data
    };
    res.json(response);
  };

  next();
});

server.use(middlewares);

// 权限校验
server.use((req, res, next) => {
  if (req.url.includes('login') && req.method === 'POST') {
    if (isAuthorized(req)) { // add your authorization logic here
      next() // continue to JSON Server router
    } else {
      res.sendStatus(401)
    }
  } else {
    next()
  }
})


// 支持加载多个db json文件
const path = require('path')
const fs = require('fs')
const mockDir = path.join(__dirname, 'data')
const files = fs.readdirSync(mockDir)
files.forEach(function (file) {
  console.log('file -----> ', file);
  const filename = file.split('.')[0]
  server.use("/" + filename, jsonServer.router(mockDir + '/' + file))
})

// 读取"C:\inetpub\wwwroot\img"
const imgPath = 'C:\\inetpub\\wwwroot\\img';
// 设置静态文件夹，这样你可以访问文件夹中的内容
server.use('/img', express.static(imgPath));
// 创建一个返回 文件夹内容 的接口
server.get('/img/*', (req, res) => {
  const requestedPath = req.params[0];
  const imgFolderPath = path.join(imgPath, requestedPath);

  // 使用 fs 模块读取文件夹内容
  const fs = require('fs');
  fs.readdir(imgFolderPath, (err, files) => {
    if (err) {
      console.error(err);
      res.status(500).send('没有该文件夹路径');
    } else {
      res.jsonp(files); // 使用 res.jsonp
    }
  });
});


// https 服务
const http = require('http');
const https = require('https');
const credentials = {
  key: fs.readFileSync('./https/tanzizhou.com.key'),
  cert: fs.readFileSync('./https/tanzizhou.com.crt'),
};

server.listen(3000, () => {
  console.log('JSON Server is running');
});
https.createServer(credentials, server).listen(5000, () => {
  console.log('https:JSON Server is running');
});